<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <el-row style="height:60px">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="hAdd" @close="hClose">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width:100%">
              <el-table-column label="序号" width="50" type="index" />
              <el-table-column label="角色名称" width="180" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作" width="300">
                <!-- slot-scope="scope" -->
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination layout="prev,pager,next" :total="total" :page-size="pageParams.pagesize" @current-change="hCurrentChange" />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色':'添加角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">保存</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
        width="30%"
      >
        <assign-permission ref="permission" :role-id="roleId" @close="showDialogAssign=false" @close-dialog="showDialogAssign=false" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialogAssign=false">取 消</el-button>
          <el-button type="primary" @click="hSave">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignPermission from './assignPermission.vue'
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roles: [],
      roleId: '',
      activeName: 'first',
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 10 // 每页两条
      },
      total: 0, // 总的数据条数
      showDialog: false,
      showDialogAssign: false, // 分配权限对话框
      isEdit: false, // 是否是编辑
      // 表单校验
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  // computed: {
  //   // 表格中最大的页码
  //   maxNum() {
  //     return Math.ceil(this.total / this.pageParams.pageSize)
  //   },
  //   // 最后一页是不是满的
  //   isLastPageFulled: function() {
  //     return this.total % this.pageParams.pageSize === 0
  //   }
  // },
  created() {
    this.loadRoles()
  },
  methods: {
    // 角色列表
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.$message.success(res.message)
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 用户点击页码，换页
    hCurrentChange(curPage) {
      // 更新页码
      this.pageParams.page = curPage
      // 重发请求
      this.loadRoles()
    },
    // 删除角色
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res, '删除请求')
        this.$message.success('删除成功')
        // 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadRoles()
      } catch (error) {
        console.log(error)
        this.$message.error('删除失败')
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑
    hEdit(row) {
      // 数据回显
      // this.roleForm = row
      this.roleForm = { id: row.id, name: row.name, description: row.description }
      this.showDialog = true
      this.isEdit = true
    },
    // 添加
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 分配权限
    hAssign(id) {
      this.roleId = id
      this.showDialogAssign = true
      this.$nextTick(() => {
        this.$refs.permission.loadPermissionByRoleId()
      })
    },
    hSubmit() {
      // 表单校验
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // 做具体的添加动作
          if (this.isEdit) {
            this.doEdit()
          } else {
            this.doAdd()
          }
        }
      })
    },
    // 保存角色权限
    hSave() {
      this.$refs.permission.hSave()
    },
    // 添加角色
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res, '添加角色')
        this.showDialog = false
        // if(表格的最后一页是满) {
        //   想查看最新添加的数据，要跳到最大页码的下一页
        //  }
        // 添加角色 角色+1
        this.total++
        // 自动跳转到最后一页
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        // 把最大页码值惊醒赋值
        this.pageParams.page = maxPage
        // console.log(this.pageParams.page)
        this.loadRoles()
        this.$message.success('添加成功')
      } catch (error) {
        this.$message.error('添加失败')
        console.log(error)
      }
    },
    // 编辑角色
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res, '修改')
        this.loadRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (error) {
        console.log(error)
        this.$message.error('编辑失败')
      }
    },
    // 关闭
    hClose() {
      // 清空表单
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>
